package www.ph.adali.happy.Utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.cash.lemoloan.statisticlib.StatisticContant;
import com.cash.lemoloan.statisticlib.Utils.PreferencesUtil;
import www.ph.adali.happy.CommonUtil;

import java.io.File;
import java.util.List;

//下载管理器
public class DownLoadUtil {


    private String downLoadUrl = "";
    private String downLoadAppName = "";
    private String installPackageName = "";
    private String fileMimeType = "application/vnd.android.package-archive";
    private DownloadManager downloadManager;
    private DownLoadManagerReceiver downLoadReceiver;
    private boolean isDownloading = false;
    private static DownLoadUtil downLoadUtil;
    private PermissionUtil permissionUtil;
    private Activity mActivity;
    private long downloadId;

    public DownLoadUtil(Activity activity) {
        mActivity = activity;
        downloadManager = (DownloadManager) activity.getBaseContext().getSystemService(Context.DOWNLOAD_SERVICE);
        permissionUtil = PermissionUtil.getInstance(activity);
    }

    public static DownLoadUtil getInstance(Activity activity) {
        if (downLoadUtil == null) {
            downLoadUtil = new DownLoadUtil(activity);
        }
        return downLoadUtil;
    }

    public String getDownLoadUrl() {
        return downLoadUrl;
    }

    public void setDownLoadUrl(String downLoadUrl) {
        this.downLoadUrl = downLoadUrl;
    }

    public String getDownLoadAppName() {
        return downLoadAppName;
    }

    public void setDownLoadAppName(String downLoadAppName) {
        this.downLoadAppName = downLoadAppName;
    }

    public String getInstallPackageName() {
        return installPackageName;
    }

    public void setInstallPackageName(String installPackageName) {
        this.installPackageName = installPackageName;
    }

    private DownloadManager.Request initDownLoadRequest() {
        if (mActivity == null || TextUtils.isEmpty(downLoadUrl)) return null;
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downLoadUrl));
        //设置漫游状态下是否可以下载
        request.setAllowedOverRoaming(false);
        request.setVisibleInDownloadsUi(true); // ANDROID9.0取消该状态,将无法查看
        request.setTitle(downLoadAppName);
        request.setDescription("DownLoading...");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType(fileMimeType);
//        getExternalStorageDirectory()对应provider的external_path
//        DebugUtil.lemonDebugD("将apk保存的sd卡位置 " + Environment.getExternalStorageDirectory().getAbsolutePath());
//        File saveFile = new File(Environment.getExternalStorageDirectory(), downLoadAppName);
//        DebugUtil.lemonDebugD("将apk文件保存的位置 " + saveFile.getAbsolutePath());
//        request.setDestinationUri(Uri.fromFile(saveFile));
//        以上注释试用于至8.0
//        该方式适配9.0以及以后
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downLoadAppName);
        return request;
    }

    private boolean checkAppInstalled() {
        if (mActivity == null || TextUtils.isEmpty(installPackageName)) return false;
        try {
            mActivity.getPackageManager().getPackageInfo(installPackageName, 0);
        } catch (Exception x) {
            return false;
        }
        return true;
    }

    private void openApp() {
        if (mActivity == null || TextUtils.isEmpty(installPackageName)) return;
        try {
            PackageManager manager = mActivity.getPackageManager();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setPackage(installPackageName);
            //查询要启动的Activity
            List<ResolveInfo> apps = manager.queryIntentActivities(intent, 0);
            //如果包名存在
            if (apps.size() > 0) {
                ResolveInfo ri = apps.get(0);
                String packageName = ri.activityInfo.packageName;
                String className = ri.activityInfo.name;
                ComponentName cn = new ComponentName(packageName, className);
                intent.setComponent(cn);
                mActivity.startActivity(intent);
            }
        } catch (Exception e) {
            DebugUtil.lemonDebugD("打开应用异常 " + e.toString());
        }
    }

    public void startDownLoad() {
        String packageName = getInstallPackageName();
        boolean installedApp = checkAppInstalled();
        DebugUtil.lemonDebugD("待下载的app包名为 " + packageName + " 待下载的app是否安装 " + installedApp);
        if (installedApp && !packageName.equals("www.ph.adali.happy")) {
            openApp();
            return;
        }
        permissionUtil.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PermissionUtil.DEFAULT_REQUEST_CODE, new PermissionUtil.OnPermissionCallback() {
            @Override
            public void onGranted(int requestCode, List<String> list) {
                if (list != null && list.size() != 0) {
                    DebugUtil.lemonDebugD("获取到写SD卡权限 是否正在下载 " + isDownloading);
                    if (downloadManager == null || isDownloading) return;
                    boolean downLoadState = checkDownloadState();
                    DebugUtil.lemonDebugD("判断系统是否支持内部组件下载 " + downLoadState);
                    if (downLoadState && !isDownloading) {
                        isDownloading = true;
                        DownloadManager.Request request = initDownLoadRequest();
                        if (request == null) return;
                        initReceiver();
                        //加入到下载的队列中。一旦下载管理器准备好执行并且连接可用，下载将自动启动。
                        registerReceiver();
                        try {
                            downloadId = downloadManager.enqueue(request);
                            Toast.makeText(mActivity, "DownLoading...", Toast.LENGTH_LONG).show();
                            DebugUtil.lemonDebugD("开始下载文件的ID " + downloadId);
                        } catch (IllegalArgumentException e) {
                            DebugUtil.lemonDebugD("没有开起download下载异常 " + e.toString());
                            showMissDownLoadManagerDialog();
                        }
                    } else {
                        CommonUtil.openBrowser(mActivity, downLoadUrl);
                    }
                }
                PreferencesUtil.putBoolean(StatisticContant.IS_GET_WRITE_EXTERNAL_STORAGE_PER, true);
            }

            @Override
            public void onDenied(int requestCode, List<String> list) {
                if (list != null && list.size() != 0) {
                    DebugUtil.lemonDebugD("没有获取到写SD卡权限 ");
                }
            }
        });
    }

    public void showMissDownLoadManagerDialog() {
        AlertDialog.Builder normalDialog = new AlertDialog.Builder(mActivity);
        normalDialog.setTitle("Please open download manager");
        normalDialog.setPositiveButton("CONFIRM",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        openDownLoadManager();
                    }
                });
        normalDialog.setNegativeButton("CANCEL",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        normalDialog.show();
    }

    private void openDownLoadManager() {
        try {
            if (mActivity != null) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
                if (intent.resolveActivity(mActivity.getPackageManager()) != null) {
                    mActivity.startActivity(intent);
                }
            }
        } catch (Exception e) {
            DebugUtil.lemonDebugD("打开设置中的DownLoadManager异常 ");
        }
    }

    //    取消下载同时下载的文件会被删除
    public void removeDownLoad() {
        if (downloadManager == null) return;
        isDownloading = false;
        downloadManager.remove(downloadId);
    }

    private void initReceiver() {
        if (downLoadReceiver == null) {
            downLoadReceiver = new DownLoadManagerReceiver();
        }
    }

    private void registerReceiver() {
        if (downLoadReceiver != null && mActivity != null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
            mActivity.registerReceiver(downLoadReceiver, filter);
        }
    }

    public class DownLoadManagerReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
                DebugUtil.lemonDebugD("用户点击了通知 " + downloadId);
                lookDownload();
            } else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                DebugUtil.lemonDebugD("广播接收下载完成 " + downloadId);
                isDownloading = false;
                unRegisterReceiver();
                checkStatus(context);
            }

        }
    }

    /**
     * 检查下载状态，是否下载成功
     */
    @SuppressLint("Range")
    private void checkStatus(Context context) {
        if (downloadManager == null) return;
        DownloadManager.Query query = new DownloadManager.Query();
        Cursor cursor = downloadManager.query(query);
        if (!cursor.moveToFirst()) {
            cursor.close();
        }
        @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
        query.setFilterById(id);
        String localFilename = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
        } else {
            localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        }
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    //下载暂停
                    break;
                case DownloadManager.STATUS_PENDING:
                    //下载延迟
                    break;
                case DownloadManager.STATUS_RUNNING:
                    //正在下载
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    DebugUtil.lemonDebugD("检查downLoadManager收到下载成功文件位置 " + localFilename);
                    installAPK(context, localFilename);
                    cursor.close();
                    break;
                case DownloadManager.STATUS_FAILED:
                    //下载失败
                    cursor.close();
                    break;
                default:
                    break;
            }
        }
    }


    private void lookDownload() {
        try {
            if (mActivity != null) {
                Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
                if (intent.resolveActivity(mActivity.getPackageManager()) != null) {
                    mActivity.startActivity(intent);
                }
            }
        } catch (Exception e) {
            DebugUtil.lemonDebugD("查看下载详情异常 ");
        }
    }

    private void unRegisterReceiver() {
        if (downLoadReceiver != null && mActivity != null) {
            mActivity.unregisterReceiver(downLoadReceiver);
            downLoadReceiver = null;
        }
    }

    /**
     * 安装apk
     */
    private static void installAPK(Context context, String path) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // Uri.parse(path).getPath()去除 file://
            File targetFile = new File(Uri.parse(path).getPath());
            if (targetFile.exists()) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", targetFile);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    context.startActivity(intent);
                } catch (Exception e) {
                    DebugUtil.lemonDebugD("安装apk异常 " + e.toString());
                }
            }
        }
    }


    /**
     * 系统的下载组件是否可用
     *
     * @return boolean
     */
    private boolean checkDownloadState() {
        try {
            int state = mActivity.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
            DebugUtil.lemonDebugD("downloadManager状态 " + state);
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
